package org.douxiaoban.client.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.google.gdata.data.douban.ReviewEntry;
import com.google.gdata.data.extensions.Rating;
import org.douxiaoban.client.R;
import org.douxiaoban.client.api.ReviewRecord;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.model.BundleSerializable;
import org.douxiaoban.client.util.ThreadTool;

//import javax.swing.text.html.HTML;
//import java.awt.im.spi.InputMethod;
//import javax.security.auth.login.Configuration;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-5-30
 * Time: 下午12:30
 */
public class PopupRecommend {

    private Context _context;
    private PopupWindow _popupWindow;
    private LayoutInflater _inflater;
    private View _view;

    private Button _reviewConfimBtn;
    private TextView _reviewContentCount;
    public PopupRecommend(Context context){
        _context = context;
    }

    /**
     * 弹出推荐对话窗口，根据横竖屏判断窗口的不同位置，内容通过回调函数传回处理
     * @param v
     * @param iRecommend 回调接口
     */
    public void showRecommendWindow(View v, final IRecommend iRecommend,
                                                                String title){
        _inflater = LayoutInflater.from(_context);
        _view = _inflater.inflate(R.layout.pop_recommend,null,true);

        Button _confirmBtn = (Button)_view.findViewById(R.id.recommend_confirm);
        Button _cancelBtn = (Button)_view.findViewById(R.id.recommend_cancel);
        final EditText _recommendTex = (EditText)_view.findViewById(R.id.recommend_text);
        TextView _recommendTtitle = (TextView)_view.findViewById(R.id.recommend_title);
        _recommendTtitle.setText(title);

        _popupWindow = new PopupWindow(_view,400,310,true);
        _popupWindow.setBackgroundDrawable(new BitmapDrawable());


            _popupWindow.showAtLocation(v, Gravity.TOP,10,100);

        //间隔半秒，等待view加载完成之后快速弹出键盘。
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                InputMethodManager m = (InputMethodManager)_recommendTex.getContext().
                getSystemService(Context.INPUT_METHOD_SERVICE);
                m.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
            }
        },500);

        _confirmBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                iRecommend.callBack(_recommendTex.getText().toString());
                _popupWindow.dismiss();
            }
        });

        _cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _popupWindow.dismiss();
            }
        });

        _popupWindow.update();
    }

    /**
     * 弹出自定义Toast窗口，在线程消息处理完返回屏幕给用户的通知
     * @param type 类型，比如表示成功或失败
     * @param content 提示的内容
     */
    public void showToastWindow(int type,String content){
        _inflater = LayoutInflater.from(_context);
        _view = _inflater.inflate(R.layout.pop_toast,null,true);
        
        TextView _popToastTx = (TextView)_view.findViewById(R.id.pop_toast_content);
        _popToastTx.setText(content);
        ImageView image = (ImageView)_view.findViewById(R.id.pop_toast_image);
        
        if(Assistant.SUCCESS_POP ==  type){
        	image.setBackgroundDrawable(_context.getResources().getDrawable(R.drawable.checkmark));
        }else if(Assistant.FAIL_POP == type){
        	image.setBackgroundDrawable(_context.getResources().getDrawable(R.drawable.checkmark_fail));
        }
        Toast toast = new Toast(_context);
        toast.setView(_view);
        toast.setGravity(Gravity.CENTER, 0, 50);
        toast.show();
        
       // _popToastTx.setText(content);
//        int width;
//        int height;
//        DisplayMetrics dm = new DisplayMetrics(); 
//        if(dm.widthPixels >= 400){
//        	width = 180;
//        	height = 180;
//        }else{
//        	width = 140;
//        	height = 140;
//        }
//        _popupWindow = new PopupWindow(_view,width,height,true);
//        _popupWindow.setBackgroundDrawable(new BitmapDrawable());
//        _popupWindow.showAtLocation(_view, Gravity.CENTER, 0, 100);
//        _popupWindow.update();
//
//        SleepThread sleepThread = new SleepThread();
//        new Thread(sleepThread).start();

        //TODO: 1.添加多种类型，失败,警告，或者滚动状态
        //TODO  2.添加动画效果 又小变大，或者震动
    }

    /**
     * 弹出发表评论窗口,需要用户提交评论名称，内容，评分,并且在接受这些数据提交后，通过
     * IRecommend 接口回调回原来的Activity 开线程处理
     * @param subjectTitle
     * @param iRecommend
     */
    public void showToashPublishReview(String subjectTitle, final IRecommend iRecommend){
        _inflater = LayoutInflater.from(_context);
        _view = _inflater.inflate(R.layout.pop_publish_review,null,true);

        final EditText _reviewTitle = (EditText)_view.findViewById(R.id.publish_review_title);
        TextView _reviewSummary = (TextView)_view.findViewById(R.id.publish_review_summary);
         _reviewConfimBtn = (Button)_view.findViewById(R.id.publihs_review_confirm);
        Button _reviewCancelBtn = (Button)_view.findViewById(R.id.publihs_review_cancel);
        final RatingBar _reviewRating = (RatingBar)_view.findViewById(R.id.publish_review_rating);
        final EditText _reviewContent = (EditText)_view.findViewById(R.id.publihs_review_content);
         _reviewContentCount = (TextView)_view.findViewById(R.id.publish_review_count);
        _reviewContent.addTextChangedListener(watcher);

        _reviewConfimBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                iRecommend.pubishReviewCallBack(_reviewTitle.getText().toString(),
                        _reviewContent.getText().toString(),
                        (int)_reviewRating.getRating());
                _popupWindow.dismiss();
            }
        });
        //点击取消按钮则关闭弹窗
        _reviewCancelBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                _popupWindow.dismiss();
            }
        });

        _reviewSummary.setText("评论 "+subjectTitle);

        _popupWindow = new PopupWindow(_view,getScreenWidth()-16, App.dip2px(_context,350),true);
        ColorDrawable dw = new ColorDrawable(-00000);
        _popupWindow.setBackgroundDrawable(dw);
        _popupWindow.showAtLocation(_view,Gravity.TOP|Gravity.CENTER,0,85);


        //间隔半秒，等待view加载完成之后快速弹出键盘。
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                InputMethodManager m = (InputMethodManager)_reviewTitle.getContext().
                getSystemService(Context.INPUT_METHOD_SERVICE);
                m.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
            }
        },500);

        _popupWindow.update();
    }

    public void showWindowReviewFull(String reviewId,IRecommend iRecommend,
                                     ReviewRecord reviewRecord,Bitmap avatar){
        _inflater = LayoutInflater.from(_context);
        _view = _inflater.inflate(R.layout.pop_full_review,null,true);

        _popupWindow = new PopupWindow(_view,440,getScreenHeight()-150,true);
        _popupWindow.setBackgroundDrawable(new BitmapDrawable());
        _popupWindow.showAtLocation(_view,Gravity.TOP|Gravity.CENTER,0,85);
        _popupWindow.update();

        final TextView reviewFullTx =
                (TextView)_view.findViewById(R.id.full_review_content);

        TextView reviewUpdate =
                (TextView)_view.findViewById(R.id.full_review_updatedate);
        TextView reviewName =
                (TextView)_view.findViewById(R.id.full_review_username);
        RatingBar ratingBar =
                (RatingBar)_view.findViewById(R.id.full_review_rating);
        TextView reviewTitle =
                (TextView)_view.findViewById(R.id.full_review_title);

        ImageView avatarImage =
                (ImageView)_view.findViewById(R.id.full_review_avatar);

        if(avatar!=null)
        avatarImage.setImageBitmap(avatar);

        reviewUpdate.setText(reviewRecord.updateDate);
        reviewName.setText(reviewRecord.author);
        reviewTitle.setText(reviewRecord.title);
        ratingBar.setRating(reviewRecord.rating);

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == Assistant.FETCH_REVIEW_FULL_DONE){
                    Bundle bundle = msg.getData();
                    BundleSerializable bs = (BundleSerializable)bundle.
                            getSerializable(Assistant.KEY_OF_SUBJECT_REVIEW);

                    _view.findViewById(R.id.full_review_content_lay).setVisibility(View.VISIBLE);
                    _view.findViewById(R.id.full_review_progress_lay).setVisibility(View.GONE);
                    reviewFullTx.setText(Html.fromHtml(bs.review));

                }else {
                    System.out.println("here");
                }
            }
        };

        ThreadTool.instace(_context).startThreadFetchReviewFull(handler,reviewId,Assistant.STATUS_BOOK);
    }


    public void showAboutWindow(){

    }

    /**
     * 监听评论内容字数，在字数达到50字则允许用户提交
     */
    private TextWatcher watcher = new TextWatcher(){

        private CharSequence temp;

        @Override
        public void afterTextChanged(Editable editable) {
            if(temp.length()>50){
                _reviewConfimBtn.setEnabled(true);
            }else {
                _reviewConfimBtn.setEnabled(false);
            }

            _reviewContentCount.setText("字数:"+temp.length());
        }

        @Override
         public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            temp = charSequence;
         }

         @Override
         public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

         }

    };

    private class SleepThread implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                _popupWindow.dismiss();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public  int getScreenWidth(){
         DisplayMetrics dm = new DisplayMetrics();
         dm = _context.getResources().getDisplayMetrics();

         return dm.widthPixels;
     }

     public  int getScreenHeight(){
         DisplayMetrics dm = new DisplayMetrics();
         dm = _context.getResources().getDisplayMetrics();
         return dm.heightPixels;
     }





}



